#!/usr/bin/env pwsh

# 参数定义
param(
    [string]$Optfunc       = $env:JIANMU_OPT_FUNC,
    [string]$VcenterServer  = $env:JIANMU_VCENTER_SERVER,
    [string]$VcenterUser    = $env:JIANMU_VCENTER_USER,
    [string]$VcenterPassword= $env:JIANMU_VCENTER_PWD,
    [string]$TargetVMName   = $env:JIANMU_VM_NAME,
    [string]$DiskPath       = $env:JIANMU_DISK_PATH
)

# 验证必需参数
$requiredParams = @(
    @{Name="Optfunc"; Value=$Optfunc},
    @{Name="VcenterServer"; Value=$VcenterServer},
    @{Name="VcenterUser"; Value=$VcenterUser},
    @{Name="VcenterPassword"; Value=$VcenterPassword},
    @{Name="TargetVMName"; Value=$TargetVMName},
    @{Name="DiskPath"; Value=$DiskPath}
)

foreach ($param in $requiredParams) {
    if ([string]::IsNullOrEmpty($param.Value)) {
        Write-Host "✗ 缺少必需参数: $($param.Name)" -ForegroundColor Red
        # 关键：先写结果文件再退出
        exit 1
    }
}

# 显示配置信息
Write-Host "=== 配置信息 ===" -ForegroundColor Cyan
Write-Host "vCenter 服务器: $VcenterServer" -ForegroundColor Gray
Write-Host "用户名: $VcenterUser" -ForegroundColor Gray
Write-Host "目标虚拟机: $TargetVMName" -ForegroundColor Gray
Write-Host "磁盘路径: $DiskPath" -ForegroundColor Gray

# 忽略证书验证
Set-PowerCLIConfiguration -InvalidCertificateAction Ignore -Confirm:$false -Scope User

# 连接vCenter
try {
    Connect-VIServer -Server $VcenterServer -User $VcenterUser -Password $VcenterPassword -ErrorAction Stop
    Write-Host "✓ vCenter 连接成功" -ForegroundColor Green
}
catch {
    Write-Host "✗ vCenter 连接失败: $($_.Exception.Message)" -ForegroundColor Red
    exit 1
}


# 根据操作类型执行对应逻辑
switch ($Optfunc.ToLower()) {
    'add' {
        Write-Host "`n=== 附加磁盘到虚拟机 ===" -ForegroundColor Cyan
        try {
            $vm = Get-VM -Name $TargetVMName -ErrorAction Stop
            $newDisk = New-HardDisk -VM $vm -DiskPath $DiskPath -Persistence Persistent -ErrorAction Stop
            Write-Host "✓ 磁盘附加成功" -ForegroundColor Green
            Write-Host "  磁盘名称: $($newDisk.Name)" -ForegroundColor Gray
            Write-Host "  文件路径: $($newDisk.FileName)" -ForegroundColor Gray
            Write-Host "  容量: $([math]::Round($newDisk.CapacityGB, 2)) GB" -ForegroundColor Gray
        }
        catch {
            Write-Host "✗ 磁盘附加失败: $($_.Exception.Message)" -ForegroundColor Red
            exit 1
        }
    }

    'delete' {
        Write-Host "`n=== 删除指定磁盘 ===" -ForegroundColor Cyan
        try {
            $vm = Get-VM -Name $TargetVMName -ErrorAction Stop
            $disk = Get-HardDisk -VM $vm | Where-Object { $_.FileName -eq $DiskPath }
            if (-not $disk) {
                Write-Host "✗ 未找到对应磁盘: $DiskPath" -ForegroundColor Red
                exit 1
            }
            Remove-HardDisk -HardDisk $disk -Confirm:$false -ErrorAction Stop
            Write-Host "✓ 磁盘已删除" -ForegroundColor Green

            Write-Host "`n重启虚拟机..." -ForegroundColor Yellow
            Restart-VM -VM $vm -Confirm:$false -ErrorAction Stop
            Write-Host "✓ 虚拟机已重启" -ForegroundColor Green
        }
        catch {
            Write-Host "✗ 磁盘删除或重启失败: $($_.Exception.Message)" -ForegroundColor Red
            exit 1
        }
    }

    default {
        Write-Host "✗ 不支持的操作类型: $Optfunc（仅支持 add/delete）" -ForegroundColor Red
        exit 1
    }
}

Write-Host "`n🎉 操作完成!" -ForegroundColor Green